<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">

            <div class="progressHint" v-if="hint">
              <NIcon size="20" class="iconStyle">
                <ErrorRound />
              </NIcon>
              <div style="white-space: pre-wrap" v-html="hint"></div>
            </div>
            <div class="progress">
              <div style="display:flex; margin-right: 10rem;">
                <NIcon :size="20" class="iconStyle">
                  <ApprovalFilled />
                </NIcon>
                <span>审批流程</span>
              </div>
              <span style="font-size: 18rem;flex: 1;" :style="{ color: !workFlowList ? 'red' : '#79bb92' }">
                {{ workFlowList ? workFlowList : '暂无配置流程，请联系管理员进行配置' }}
              </span>
            </div>

            <div class="content_cen">
              <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules" :label-width="110"
                :model="formValue" style="width: 350rem" label-align="right">


                <!-- <NFormItem label="涉密类型:">
                  <NSelect :options="isSecretList" class="commonWidth" clearable v-model:value="formValue.isSecret" />
                </NFormItem> -->
                <div v-if="formValue.isSecret == '涉密'">
                  <NFormItem label="收发文单位:" path="sendUnit">
                    <NInput placeholder="请输入收发文单位" :allow-input="stopNull" class="commonWidth"
                      v-model:value="formValue.sendUnit" />
                  </NFormItem>
                  <NFormItem label="份数:" path="copies">
                    <NInput placeholder="请输入份数" class="commonWidth" :allow-input="onlyNumber"
                      v-model:value="formValue.copies" />
                  </NFormItem>
                </div>
                <div v-if="formValue.isSecret == '非涉密'">
                  <NFormItem label="使用时间:" path="useTime">
                    <NDatePicker input-readonly placeholder="请选择使用时间" class="commonWidth" type="date"
                      v-model:formatted-value="formValue.useTime" clearable :is-date-disabled="handleDateA" />
                  </NFormItem>
                  <NFormItem label="返还时间:" path="backTime">
                    <NDatePicker input-readonly placeholder="请选择返还时间" class="commonWidth" type="date"
                      v-model:formatted-value="formValue.backTime" clearable :is-date-disabled="handleDate" />
                  </NFormItem>
                </div>
                <NFormItem label="档案名称:" path="archiveName">
                  <NEllipsis class="commonWidth" style="max-width: 240rem;">
                    {{formValue.archiveName}}
                  </NEllipsis>
                  <!-- <NInput class="commonWidth" :disabled="true" v-model:value="formValue.archiveName" /> -->
                </NFormItem>
                <NFormItem label="卷内档号:" path="archiveId">
                  <NInput placeholder="请输入卷内档号" class="commonWidth" v-model:value="formValue.archiveId" :on-update:value="handleSearchArchive"/>
                </NFormItem>
                <NFormItem label="档案使用用途:" path="archiveUse">
                  <NInput placeholder="请输入档案使用用途" :allow-input="stopNull" class="commonWidth"
                    v-model:value="formValue.archiveUse" type="textarea" />
                </NFormItem>
                <NFormItem label="使用方法:" path="useType">
                  <NSelect :options="typeList" class="commonWidth" clearable v-model:value="formValue.useType" />
                </NFormItem>
                <NFormItem label="附件:" path="fileId">
                  <VUpload :file-list="fileList" @getList="handleUploadList" />
                </NFormItem>
              </NForm>
            </div>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <div style="display: flex">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
          <template #icon>
            <img :src="VBackImg" style="width: 25rem; height: 25rem" />
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" style="background-color: #5faab1;" @click="confirm(true)" :loading="loading"
          v-if="workFlowList">
          保存草稿
        </NButton>
        <NButton type="primary" @click="confirm(false)" :loading="loading" v-if="workFlowList">
          提交申请
        </NButton>
      </NSpace>
    </div>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againConfirm" title="保存提示">
      <div v-if="formValue.isSecret == '非涉密' || formValue.draft"
        style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{ contentContent }}
      </div>
      <div v-else>
        <NForm label-placement="left" label-width="80" size="small" style="min-width: 500px">
          <NFormItem>经办人承诺:</NFormItem>
          <NFormItem>1.本文件只限于上述用途，绝不做他用。</NFormItem>
          <NFormItem>
            2.本文件只限在办公室使用，并按保密文件存放，绝不再次复印，不携带外出。
          </NFormItem>
          <NFormItem>3.本文件如有遗失、泄密，本人自愿承担全部责任。</NFormItem>
        </NForm>
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  useMessage,
  NModal,
  NSelect,
  NDatePicker,
  NSpin,
  NIcon,
  NEllipsis,
  type FormInst
} from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute } from 'vue-router'
import VUpload from '@/views/OA/Common/Upload.vue'
import type { FormRules } from 'naive-ui'
import { workFlow } from '@/enums/workFlow'
import { ApprovalFilled } from '@vicons/material'
import { ErrorRound } from '@vicons/material'
import { subDays } from 'date-fns'

const route = useRoute()
const tags = useTagStore().tags
const message = useMessage()
import VBackImg from '@/assets/images/back.png'

const handleSearchArchive = (key: string) => {
  formValue.archiveId = key
  if(!key || key === '') {
    formValue.archiveName = null
    return false
  }
  const re = Idoption.value.find((v: any) => {
    return v.archiveId === formValue.archiveId
  })
  formValue.archiveName = re ? (re.archiveName || null) : null
}

//只能输入数字
const onlyNumber = (value: string) => {
  var regA = /^\d*\.{0,1}\d{0,2}$/
  return !value || regA.test(value)
}

//去除空格
const stopNull = (value: string) => {
  return !value.startsWith(' ') && !value.endsWith(' ')
}

const props = defineProps({
  title: { type: String, default: () => '档案借阅申请' },
  id: { type: [Number, String], default: () => null },
  flag: { type: [Number, String], default: () => null }
})

const spinShow = ref(false)

// 日期禁用
const handleDate = (ts: any) => {
  return ts < new Date(subDays(new Date(formValue.useTime), 1))
}

const handleDateA = (ts: any) => {
  if (formValue.returnTime) {
    return ts > new Date(new Date(formValue.returnTime))
  } else {
    return false
  }
}

const formValue = reactive<Record<string, any>>({
  draft: null, //草稿状态
  entityId: null, //流程实体id

  isSecret: '非涉密', //涉密类型
  sendUnit: null, //收发文单位
  copies: null, //份数
  useTime: null, //使用时间
  backTime: null, //返还时间

  archiveId: null, //档案id
  archiveName: null, //档案名称
  archiveUse: null,  //档案使用用途
  useType: null, //使用方式
  fileId: null
})

const searchOptions = ref<any>([])

const rules: FormRules = {
  sendUnit: {
    required: false,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      // if (!value) return new Error('请输入收发文单位')
      if (value?.length > 100) return new Error('收发文单位不得超过100字')
      return true
    }
  },
  copies: {
    required: false,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (value?.length > 100) return new Error('份数不得超过100字')
      return true
    }
  },
  archiveId: {
    required: true,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if(!value || value?.length ===0) return new Error('请输入卷内档号')
      const re = Idoption.value.find((v: any) => {
        return v.archiveId === value
      })
      if(!re) return new Error('请输入正确的卷内档号')
      return true
    }
  },
  archiveUse: {
    required: false,
    trigger: ['change', 'input'],
    validator: (_: any, value: any) => {
      if (value?.length > 100) return new Error('档案使用用途不得超过100字')
      return true
    }
  },
  // archiveName: {
  //   required: true,
  //   trigger: ['change', 'blur'],
  //   validator: (_: any, value: any) => {
  //     if (!value) return new Error('请输入档案名称')
  //     if (value?.length > 100) return new Error('档案名称不得超过100字')
  //     return true
  //   }
  // },
  useTime: {
    required: true,
    message: '使用时间不能为空',
    trigger: ['blur', 'change']
  },
  backTime: {
    required: true,
    message: '返还时间不能为空',
    trigger: ['blur', 'change']
  }
}

const isSecretList = [
  {
    value: '涉密',
    label: '涉密'
  },
  {
    value: '非涉密',
    label: '非涉密'
  }
]

const typeList = [
  {
    value: '查阅',
    label: '查阅'
  },
  {
    value: '复印',
    label: '复印'
  },
  {
    value: '摘抄',
    label: '摘抄'
  }
]


const Idoption: any = ref()
const getSelect = async () => {
  const [error, res] = await sendRequest({
    module: 'file',
    api: 'idSelect',
    override: {
      params: {
        isSecret: formValue.isSecret,
        limit: 999999,
        page: 1
      }
    }
  })
  if (error) return
  Idoption.value = res
}
getSelect()

const IdoptionA: any = ref()
const getSelectA = async (val: any) => {
  const [error, res] = await sendRequest({
    module: 'file',
    api: 'idSelect',
    override: {
      params: {
        id: val
      }
    }
  })
  if (error) return
  IdoptionA.value = res
}

const changeName = (_: any, info: any) => {
  return;
  getSelectA(info.id)
  formValue.archiveId = ''
}

// 获取流程id
const hint = ref()
const workFlowList = ref(' ')
const getWorkFlow = async () => {
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'workFlow',
    override: {
      params: {
        functionCode: workFlow.DAJYSQLC
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  formValue.entityId = res.data.entityId
  hint.value = res.data.remark
  workFlowList.value = res.data.workFlowList?.length ? res.data.workFlowList?.map((it: any) => it).join(' → ') : null
}
getWorkFlow()

//获取详情
const getInfo = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest({
    module: 'file',
    api: 'fileItem',
    uri: {
      id: props.id as never
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  fileList.value = res.data?.fileList
  Object.keys(formValue).map((it: any) => {
    // @ts-ignore
    formValue[it] = res.data[it]
  })
  await getWorkFlow()
  spinShow.value = false
}

// 附件
const fileList = ref()
const handleUploadList = (v: any) => (formValue.fileId = v)

// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}

// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const modalVisible = ref(false)
const contentContent = ref()
const confirm = (status: boolean) => {
  formValue.draft = status
  formRef.value?.validate(async (err) => {
    if (err) return
    contentContent.value = status ? '您确定要保存草稿吗？' : ' 您确定要提交申请吗？'
    modalVisible.value = true
  })
}

const againConfirm = async () => {
  if (props.id && !props.flag) {
    const [error, res] = await sendRequest({
      module: 'file',
      api: 'fileUpdate',
      override: {
        data: {
          ...formValue,
          id: props?.id
        }
      }
    })
    modalVisible.value = false
    if (error) return message.error(error.message)
    if (res.code) return message.error(res.data)
    message.success(res.msg)
  } else {
    const [error, res] = await sendRequest({
      module: 'file',
      api: 'fileSave',
      override: {
        data: formValue
      }
    })
    modalVisible.value = false
    if (error) return message.error(error.message)
    if (res.code) return message.error(res.data)
    message.success(res.msg)
  }
  goRun()
}

const goRun = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  router.push({ path: '/OA/File/FileList' })
}

// //提交完跳转我的提交
// const goSubmit = () => {
//   const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
//   tags.splice(index, 1)
//   if (formValue.draft) return router.push({ path: '/OA/UserCenter/Drafts' })
//   router.push({ path: '/OA/UserCenter/Submit' })
// }


watch(
  () => formValue.isSecret,
  () => {
    if (formValue.isSecret == '涉密') {
      formValue.useTime = null
      formValue.backTime = null
    } else {
      formValue.sendUnit = null
      formValue.copies = null
    }
  }
)

// watch(
//   () => route,
//   () => {
//     if (route.path == '/OA/File/FileEdit' && props.title == '档案借阅申请编辑' && props.id) {
//       getInfo()
//     }
//   },
//   { deep: true, immediate: true }
// )
watch(
  () => props.id,
  () => {
    if (props.title == '档案借阅申请编辑' && props.id) getInfo()
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 240rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    border-bottom: 1px solid #fff;
    padding: 15rem 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      flex-wrap: wrap;
      padding: 20rem 0 180rem;
      background-color: #ebeceb;


      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 5px 10rem;
          margin-bottom: 10rem;
        }
      }
    }
  }
}

.content_cen {
  display: flex;
  flex-direction: column;
  margin-left: 35%;
}

.iconStyle {
  margin-right: 5rem;
  color: #5fb17f;
}

.progress {
  display: flex;
  align-items: center;
  min-width: 350rem;
  max-width: 800rem;
  min-height: 50rem;
  background-color: #d5e2d8;
  border-radius: 5rem;
  margin-bottom: 10px;
  padding: 5px 15px;
  margin-left: 35%;
}

.progressHint {
  display: flex;
  min-width: 350rem;
  max-width: 800rem;
  padding: 5px 15px;
  margin-left: 35%;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
